<?php
/*
 * Session functions
 * Henrik Volckmer
 */
require_once('database.php');

/* Creates a new, secure session */
function session_create()
{
	include('config.php');
	session_start(); // no error checking, always returns true.
	
	// Create a new session in the database
	$ip = $_SERVER['REMOTE_ADDR'];
	$hostname = gethostbyaddr($ip);
	$agent = $_SERVER['HTTP_USER_AGENT'];
	
	$query = 'INSERT INTO '.$table_prefix.'_sessions (sid, time, ip, hostname, agent, uid) VALUES ("'.session_id().'",'.time().',"'.$ip.'","'.$hostname.'","'.$agent.'",0)';
	db_query($query);
}

/* Continues the current session if available
 * Uses sid regen + ip/agent checking for security
 * 
 * Return values:
 * 0 - success
 * 1 - session does not exist
 * 2 - agent (browser) changed
 * 3 - ip changed
 * 4 - hostname changed
 * 5 - ip and hostname changed
 */
function session_continue()
{
	session_start(); // continue the current session
	include('config.php');
	
	// Get user info and ip
	$ip = $_SERVER['REMOTE_ADDR'];
	$hostname = gethostbyaddr($ip);
	$agent = $_SERVER['HTTP_USER_AGENT'];
	
	// Query database to get previous and compare it to the new ip and agent
	$query = 'SELECT ip, hostname, agent FROM '.$table_prefix.'_sessions WHERE sid = "'.session_id().'"';
	$result = db_query($query);
	
	// if session doesn't exist in database
	if (mysql_num_rows($result) == 0)
	{
		// create a new session
		session_create();
		return 1;
	}
	
	// if user agent (browser) changed
	if ($agent != mysql_result($result, 0, 'agent'))
	{
		return 2;
	}

	// ip/hostname variables
	$ip_change = false;
	$hostname_change = false;
	
	// if user ip changed
	if ($ip != mysql_result($result, 0, 'ip'))
	{
		$ipchange = true;
	}
	// if hostname changed
	if ($hostname != mysql_result($result, 0, 'hostname'))
	{
		$hostname_change = true;
	}
	
	// return if only ip changed
	if ($ip_change && !$hostname_change)
	{
		return 3;
	}
	
	// return if only hostname changed
	if (!$ip_change && $hostname_change)
	{
		return 4;
	}
	
	// return if both ip and hostname changed (very bad)
	if ($ip_change && $hostname_change)
	{
		return 5;
	}
	
	// Regen session id for security after host/ip have been verified
	$old_sid = session_id();
	$success = session_regenerate_id(true); // get a new session id
	if (!$success)
	{
		die('Could not update session.');
	}

	// Update the sid in the database
	$query = 'UPDATE '.$table_prefix.'_sessions SET sid = "'.session_id().'" WHERE sid = "'.$old_sid.'"';
	db_query($query);
	
	return 0;
}

// Terminates a session based on a given id
function session_terminate($sid)
{
	$query = 'DELETE FROM '.$table_prefix.'_sessions WHERE sid = '.$sid;
	db_query();

	session_close();
}

?>